#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2021/11/12 13:11
    Desc  :
--------------------------------------
"""
from platform_auth.settings import BASE_DIR
from concurrent_log_handler import ConcurrentRotatingFileHandler


import logging
import threading
import uuid

thread_log = threading.local()
thread_log.traceId = None
thread_log.requestInfo = None


class CustomerFilter(logging.Filter):
    DEFAULT_TRACE_ID = str(uuid.uuid4())[-12:]
    DEFAULT_REQUEST = None

    def filter(self, record: logging.LogRecord) -> bool:
        record.traceId = thread_log.traceId if thread_log.traceId else self.DEFAULT_TRACE_ID
        record.requestInfo = thread_log.requestInfo if thread_log.requestInfo else self.DEFAULT_REQUEST
        return True


class Logger(logging.Logger):
    FORMAT = '%(asctime)s | %(levelname)s | %(traceId)s | %(filename)s:%(lineno)d | %(requestInfo)s | - %(message)s'

    def __init__(self, name, logfile):
        logging.Logger.__init__(self, name, logging.DEBUG)
        log_format = logging.Formatter(fmt = self.FORMAT, datefmt = '%Y-%m-%d %H:%M:%S')
        # 输出
        console = logging.StreamHandler()
        console.setFormatter(log_format)
        # 输出到文件
        handler_file = ConcurrentRotatingFileHandler(logfile, "a", 512 * 1024, 5, encoding = 'utf-8')
        handler_file.setFormatter(log_format)
        self.addHandler(console)
        self.addHandler(handler_file)
        self.addFilter(CustomerFilter())


logger = Logger(name = 'pioneer', logfile = rf'{BASE_DIR}/logs/app.log')